import { clearJson } from '@utils'
import { dayjs } from 'element-plus'

import { auditCountApi, pageApi, getGroupAppliesApi } from '@/api/apply'
import { APPLY_TYPE } from '@/common/enums/apply'

export const useApplyStore = defineStore('apply', {
  state: () => ({
    auditCount: 0,
    active: null,
    list: [],
    groupApplies: [], // 群聊申请列表
  }),
  getters: {
    filteredList: (state) => {
      const oneYearAgo = dayjs().subtract(1, 'year')
      // 合并好友申请和群聊申请
      const allApplies = [...state.list, ...state.groupApplies]
      return allApplies.filter(item => {
        // 待审核的申请全部显示
        if (item.status === 0) return true
        // 已处理的申请只显示最近一年的
        return dayjs(item.createdAt).isAfter(oneYearAgo)
      }).sort((a, b) => {
        // 按创建时间降序排序
        return new Date(b.createdAt) - new Date(a.createdAt)
      })
    }
  },
  actions: {
    /**
     * 获取待审核数量
     */
    async getAuditCount() {
      const r = await auditCountApi()
      if (r) {
        this.auditCount = r.data
      }
    },
    /**
     * 获取消息列表
     * @param {*} size 数据量
     * @returns
     */
    async getList(size = 10) {
      let lastId = ''
      const length = this.list.length
      if (length) {
        lastId = this.list[length - 1].id
      }
      const r = await pageApi({ lastId, size })
      if (r) {
        this.list.push(...r.data)
        
        // 获取群聊申请列表
        await this.getGroupApplies()
        
        return r.data
      }
    },
    /**
     * 获取群聊申请列表
     */
    async getGroupApplies() {
      try {
        // 获取待审核的群聊申请
        const r = await getGroupAppliesApi({ 
          status: 0, 
          page: 1,
          page_size: 50 
        })
        
        if (r && (r.code === 0 || r.code === 200) && r.data && r.data.list) {
          // 转换格式，使其与好友申请格式一致
          const formattedApplies = r.data.list.map(apply => ({
            id: apply.id,
            userId: apply.userId,
            content: apply.content || '申请加入群聊',
            status: apply.status,
            createdAt: apply.createdAt,
            type: APPLY_TYPE.GROUP,
            isApplicant: apply.isApplicant, // 是否为申请人
            user: {
              id: apply.userId,
              nickname: apply.nickname,
              avatar: apply.avatar,
              sex: 0,
              online: 1
            },
            room: {
              id: apply.roomId || 0,
              name: apply.roomName || '群聊',
              avatar: apply.roomAvatar || ''
            }
          }))
          
          this.groupApplies = formattedApplies
          console.log('群聊申请列表:', this.groupApplies)
        }
      } catch (error) {
        console.error('获取群聊申请列表失败:', error)
      }
    },
    /**
     * 新增需求
     * @param {*} apply 
     */
    addApply(apply) {
      // 判断是否为群聊申请
      if (apply.type === APPLY_TYPE.GROUP) {
        // 避免重复添加
        const exists = this.groupApplies.some(item => item.id === apply.id)
        if (!exists) {
          this.groupApplies.unshift(apply)
        }
      } else {
        // 好友申请
        const exists = this.list.some(item => item.id === apply.id)
        if (!exists) {
          this.list.unshift(apply)
        }
      }
      this.auditCount += 1
    },
    /**
     * 设置选中
     * @param {*} apply 
     */
    setActive({ id }) {
      // 先从好友申请中查找
      let apply = this.list.find(item => item.id === id)
      
      // 如果没找到，从群聊申请中查找
      if (!apply) {
        apply = this.groupApplies.find(item => item.id === id)
      }
      
      this.active = apply
    },
    /**
     * 设置状态
     * @param {*} id 
     * @param {*} status 
     */
    setStatus(id, status) {
      // 先尝试更新好友申请状态
      let apply = this.list.find(item => item.id === id)
      if (apply) {
        apply.status = status
      } else {
        // 尝试更新群聊申请状态
        apply = this.groupApplies.find(item => item.id === id)
        if (apply) {
          apply.status = status
        }
      }
      
      this.auditCount = this.auditCount > 0 ? this.auditCount - 1 : 0
    },
    /**
     * 更新用户在线状态
     * @param {*} userId 用户ID
     * @param {*} online 在线状态
     */
    updateUserOnline(userId, online) {
      // 更新好友申请中的用户状态
      for (let i = 0; i < this.list.length; i++) {
        const { user } = this.list[i];
        if (user && user.id === userId) {
          user.online = online
        }
      }
      
      // 更新群聊申请中的用户状态
      for (let i = 0; i < this.groupApplies.length; i++) {
        const { user } = this.groupApplies[i];
        if (user && user.id === userId) {
          user.online = online
        }
      }
    },
    /**
     * 清除数据
     */
    clear() {
      clearJson(this.$state)
    }
  }
})
